# -*- coding: UTF-8 -*-import os
import shutil
import pymysql
from libs.config import host, user, pwd, port, db_name


def insertCorp(db, uuid, type, corpId, agentId, secret, token, aesKey):
    c = db.cursor()
    insertSql = "insert into pm_app_corp(uuid, type, corpId, agentId, secret, token, aesKey, create_time, update_time) values('{}', {}, '{}', {}, '{}', '{}', '{}', now(), now())".format(uuid, type, corpId, agentId, secret, token, aesKey)
    updateSql = "update pm_app_corp set agentId={}, secret='{}', token='{}', aesKey='{}', update_time=now() where uuid='{}' and type={}".format(agentId, secret, token, aesKey, uuid, type)
    try:
        c.execute(insertSql)
        db.commit()
    except Exception as e:
        print("{}pm_app_corp存储失败: {}".format(uuid, e))
        db.rollback()
        c.execute(updateSql)
        db.commit()
    c.close()


def insertAuth(db, uuid, principal_name, appId, type=2, enterprise_id=90, authorizer_status=1):
    c = db.cursor()
    insertSql = "insert into pm_app_auth(uuid, appId, type, authorizer_time, create_time, update_time, enterprise_id, authorizer_status, principal_name) values('{}', '{}', {}, now(), now(), now(), {}, {}, '{}')".format(uuid, appId, type, enterprise_id, authorizer_status, principal_name)
    try:
        c.execute(insertSql)
        db.commit()
    except Exception as e:
        print("{}pm_app_auth存储失败: {}".format(uuid, e))
        db.rollback()
    c.close()

# cursor.execute('select * from pm_app_corp')
# aa = cursor.fetchone()
# print(aa)
# cursor.execute('select name,age from person')
# for i in range(aa[0]):
#     a, b = cursor.fetchone()
#     c = "我的名字叫{}，今年{}岁".format(a, b)
#     print(c)
## db.close()


def getItems():  # 获取应用名称,应用介绍选填)
    itemTitle = "AW大师"
    itemText = "2020/5/22/1"
    return itemTitle, itemText


def saveQRCodeUrl(qr_code_url, uuid, type=2):  # 保存登录二维码
    db = pymysql.connect(host=host, user=user, db=db_name, password=pwd, port=port, charset='utf8')
    c = db.cursor()
    updateSql = "update pm_app_qrcode set qrcode_url='{}', update_time=now() where uuid='{}' and type={}".format(qr_code_url, uuid, type)
    try:
        c.execute(updateSql)
        db.commit()
    except Exception as e:
        print("{}登录二维码更新失败: {}".format(uuid, e))
        db.rollback()
    c.close()
    db.close()

def makeDir(newPath):
    try:
        os.makedirs(newPath)
    except:
        shutil.rmtree(newPath)
        os.makedirs(newPath)


def moveFiles(oldPath, newPath):
    filelist = os.listdir(oldPath)
    for files in filelist:
        filename1 = os.path.splitext(files)[1]  # 读取文件后缀名
        filename0 = os.path.splitext(files)[0]  # 读取文件名
        m = filename1 == '.txt' or filename1 == '.png'
        if m:
            full_path = os.path.join(oldPath, files)
            despath = os.path.join(newPath, files)
            shutil.move(full_path, despath)
        else:
            continue

